#----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# ADsyncXML script
# Author: Ronald Bruinsma (SharePoint consultant - iDocs)
# Date:   Februari 2013
# Version: 1.0
#----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Get-Module -ListAvailable | Import-Module
. D:\sync\functions.ps1

#Setting XML file
$xmlFileImport = "D:\sync\ADsyncXML_settings.xml"

[xml]$xmlConfigFile = Get-Content $xmlFileImport
 
#begin, LogFile
$logFilePath = $xmlConfigFile.config.logfilepath
$logfile = $xmlConfigFile.config.logfilename
$logfileretention = $xmlConfigFile.config.logfileretention
$dateNow = get-date;   
#create the logfile with timestamp
$logFileName = $logfile + $datenow.ToString('yyyy-MM-dd-hh-mm-ss') + ".txt";
$logFileText = "AD Import Sync: " + $datenow.ToString('yyyy-MM-dd-hh-mm-ss') + "`r`n";
new-item -path $logFilePath -name $logFileName  -type "file" -value $logFileText;
$global:logfilefinalpath = $logFilePath + "\" + $logFileName;
   
Log-ScreenFile("reading the list of fields to import from the config file")
$fields = $xmlConfigFile.config.fields.split(";");Log-ScreenFile("Fields to import: $fields")
$runcount = $xmlConfigFile.config.runcount;Log-ScreenFile("script is going to process the amount of users: $runcount")
#file input variables
$input_file = $xmlConfigFile.config.source.inputfile;Log-ScreenFile("Input file is:$input_file")
$input_type = $input_file.inputtype;Log-ScreenFile("Input type is:$input_type")
$input_filename = $input_file.filename;Log-ScreenFile("Import file name is: $input_filename")
$input_path = $input_file.inputpath;Log-ScreenFile("input path is:$input_path")
$input_importshare = $input_file.importshare;Log-ScreenFile("Get the xml file from share: $input_importshare")
$input_archivepath = $input_file.archivepath;Log-ScreenFile("archive path is:$input_archivepath")
$input_archiveretention = $input_file.archiveretention;Log-ScreenFile("archive retention period:$input_archiveretention")
$input_schemafile = $input_file.schemafile;Log-ScreenFile("schema file is:$input_schemafile")
$input_totalfilename = $input_path + "\" + $input_filename;Log-ScreenFile("File to process will be: $input_totalfilename")
#ad export variables
$target_location=$xmlConfigFile.config.target.targetlocation;Log-ScreenFile("targetlocation is:$target_location")
$target_type = $target_location.targettype;Log-ScreenFile("target type is:$target_type")
$target_server = $target_location.targetserver;Log-ScreenFile("target server is:$target_server")
$target_container = $target_location.targetcontainer;Log-ScreenFile("target location is:$target_container")
$target_filter = $target_location.targetfilter;Log-ScreenFile("target filter is:$target_filter")

Log-ScreenFile("Importing the xml input file $input_totalfilename")
try
{
	[xml]$employees =  Get-Content $input_totalfilename;
}
catch
{
	Log-ScreenFile($Error[0].Exception);
}
$records = $employees.ROWSET.ROW #read all users in xml

#start check users in AD and compare the attributes with the import xml
foreach($employee in $records) #loop through all users
{       
    $id = $employee.LOGINNAME
    Log-ScreenFile("Search query on AD for user: Get-ADUser -Filter {$target_filter -eq $id} -Server $target_server -SearchBase $target_container")
    $usr = Get-ADUser  -Filter {$target_filter -eq $id} -Server $target_server -SearchBase $target_container -Properties *
   
    if($usr -ne $null) #user does exists in Active Directory, now check the properties of the user are the same as in the XML
    {
		Log-ScreenFile("The user $id exists in Active Directory")
		 $updateprops = New-Object Hashtable;
		 
		foreach($field in $fields) #check each property
		{
			if ($employee.$field -ne "")
			{
       			if($usr.$field -ne $employee.$field) #check is something is different and needs to be append in AD
				#AD user property is different from the XML property, so change the property in AD
				{
				$updateprops.Add($field,$employee.$field);
				}
			}
		}
		if($updateprops.count -gt 0)
    	{
			Set-ADUser $usr.SamAccountName -Replace $updateprops; # Replace changed user properties.
		}
		#log the update properties:
		$updateprops.GetEnumerator() | ForEach-Object{
			Log-ScreenFile("Changed property: " + $_.Key + " for user " + $usr.DistinguishedName + " with value: " + $_.Value )
		}
		$updateprops.Clear();
		
 ####quote this code if you do not update the manager attribute in AD
		#update the MANAGER field
		$distinguisheduser = Get-DistinguishedName $employee.MANAGER
		#check if manager field from ad difference from PIMS output.
		if($usr.Manager -ne $distinguisheduser)
		{
			#update managerfield in AD
			Set-ADUser $usr.SamAccountName -Manager $distinguisheduser 
			#write logging
			Log-ScreenFile("Changed property: MANAGER " + " for user " + $usr.DistinguishedName + " with value: " + $distinguisheduser )
		}
 ####quote this code if you do not update the manager attribute in AD
    }
    else
    { 
        Log-ScreenFile("The user $id does not exists in Active Directory")
        # goto next user
    }
}

#delete or archive old log files. Use retention time in settings xml
try
{
	#TXT files
	$lastmod = $dateNow.AddDays(-$logfileretention);
	$filter = "*.txt";
	#get all files based on retention date and file extension
	$files = Get-Childitem $logFilePath -Include $filter -Recurse | Where {$_.LastWriteTime -le "$lastmod"}
	#delete files
	foreach($file in $files)
	{
	    if($ffile -ne "")
	    {
	    	Log-ScreenFile ("Removing old file $file");
	    	Remove-Item $file.FullName | out-null;
	    }
	    else
	    {
	       Log-ScreenFile ("No files will be deleted because no file is older than the retention value");
	    }
	}
}
catch
{
	Log-ScreenFile($Error[0].Exception);
}
try
{
	#XML logging
	$filter = "*.xml";
	#get all files based on retention date and file extension
	$files = Get-Childitem $logFilePath -Include $filter -Recurse | Where {$_.LastWriteTime -le "$lastmod"}
	#delete files
	foreach($file in $files)
	{
	    if($ffile -ne "")
	    {
	    	Log-ScreenFile ("Removing old file $file");
	    	Remove-Item $file.FullName | out-null;
	    }
	    else
	    {
	       Log-ScreenFile ("No files will be deleted because no file is older than the retention value");
	    }
	}
}
catch
{
	Log-ScreenFile($Error[0].Exception);
}

################# DONE ####################

